package org.example.controller;

import org.example.common.Result;
import org.example.common.config.JwtTokenUtils;
import org.example.entity.Account;
import org.example.entity.Admin;
import org.example.entity.User;
import org.example.service.AdminService;
import org.example.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/account")
public class AccountController {
    @Resource
    AdminService adminService;

    @Resource
    UserService userService;


    /**
    * 注册接口
    */
    @PostMapping("/register")
    public Result accountRegister(@RequestBody Account account){
        User user = new User();
        BeanUtils.copyProperties(account,user);
        Account adduser = userService.addUser(user);
        return Result.success(adduser);
    }


    /**
    * 用户登录接口
    * **/
    @PostMapping("/login")
    public Result AcountLogin(@RequestBody Account account){
    Integer role = account.getRole();
    Account login = new Account(); // 定义一个Account类的login,用于返回给前端
    if ( 1 == role){
        Admin admin = new Admin(); //创建一个管理员类admin
        BeanUtils.copyProperties(account,admin); //把父类的属性拷贝到admin
        login = adminService.adminLogin(admin); //调用服务层的登录逻辑
    }
    if ( 2 == role){
        User user = new User();
        BeanUtils.copyProperties(account,user);
        login = userService.userLogin(user);
    }

    //生成token
    String token = JwtTokenUtils.genToken(login.getId() + "-" + login.getRole(), login.getPassword());
    //创建一个键值对map集合，把token和user塞进去，返回给前端
    Map<String, Object> map = new HashMap<>();
    map.put("token", token);
    map.put("user", login);
    return Result.success(map);   //封装好数据后，把map集合返回给欸前端。
    }

    /**
     * 新增管理员接口
     */
    @PostMapping("/addadmin")
    public Result adminRegister(@RequestBody Admin admin){
        return Result.success(adminService.adminRegister(admin));
    }
}
